package com.aura.blog.common.interceptor;


import com.aura.blog.common.constant.Constants;
import com.aura.blog.common.util.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 登录拦截器
 * 用于拦截需要认证的请求，验证用户是否已登录
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 在请求处理之前进行调用
     *
     * @param request  当前HTTP请求
     * @param response 当前HTTP响应
     * @param handler  被调用的处理器对象
     * @return true表示继续流程，false表示中断流程
     * @throws Exception 异常
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userToken = request.getHeader(Constants.HEADER_USER_TOKEN_KEY);
        log.info("从header中获取到token. url:{}, userToken:{}", request.getRequestURI(), userToken);
        Boolean checkToken = JwtUtils.check(userToken);
        if (!checkToken) {
            log.error("token校验失败, token:{}", userToken);
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        return true;
    }
}
